//
//  FindFrinedsViewController.m
//  BigPinwheel
//
//  Created by 徐伟 on 16/2/20.
//  Copyright © 2016年 leita. All rights reserved.
//

#import "FindFrinedsViewController.h"
#import "InscriptionManager.h"
#import "ChatListCell.h"
#import "QualifyFilterView.h"
#import "MyFriendsHeaderView.h"
#import "NameCardViewController.h"
#import "WSocket.h"

@interface FindFrinedsViewController ()

@property(strong,nonatomic)InscriptionManager *inspManager;
@property(strong,nonatomic)WSocket *wSocket;
@property(strong,nonatomic)MyFriendsHeaderView *headerView;
@property(strong,nonatomic)QualifyFilterView *filterView;

@property(strong,nonatomic)POPBasicAnimation *downAnimation;
@property(strong,nonatomic)POPBasicAnimation *upAnimation;
@property(strong,nonatomic)POPBasicAnimation *fadeInAnimaiton;
@property(strong,nonatomic)POPBasicAnimation *fadeOutAnimation;

@property(assign,nonatomic)int sex;
@property(assign,nonatomic)int identity;
@property(assign,nonatomic)int place;
@property(assign,nonatomic)int fromprice;
@property(assign,nonatomic)int endprice;

@end

@implementation FindFrinedsViewController

- (void)dealloc
{
    NSLog(@"朋友筛选界面释放");
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}

#pragma mark -本类接受的通知
-(void)loginSuccessed:(NSNotification *)noti
{
   dispatch_async(dispatch_get_main_queue(), ^{
       
       [self refreshNewestFriends:nil];
   });
}

//获取最新的农民司机列表
-(void)refreshNewestFriends:(NSNotification *)noti
{
    dispatch_sync(_inspManager.getFriendQueue, ^{
        
     [[WSocket sharedWSocket]QueryUsersByLocation:0 :0 :2 :@"" :@"" :1 :45 DfcQueryUsersByLocationBlock:^(int ret, NSDictionary *rootDict) {
         
         if (ret>=0) {
             
             if (_dataArray) {
                 [_dataArray removeAllObjects];
             }
             
             for (NSDictionary *dict in [rootDict objectForKey:@"dfc_users"])
             {
                 DFCUserInfo *userinfo = [[DFCUserInfo alloc]init];
                 [userinfo setValuesForKeysWithDictionary:dict];
                 userinfo.head_portrait = [rootDict objectForKey:@"head_path"];
                 userinfo.phone_num = [rootDict objectForKey:@"user_id"];
                 [_dataArray addObject:userinfo];
             }
             NSLog(@"daaaa = %@",_dataArray);
             
             dispatch_async(dispatch_get_main_queue(), ^{
                 [_tableView reloadData];
             });
         }
         
     }];
});
}

-(instancetype)init
{
    self = [super init];
    if (self)
    {
        _inspManager = [InscriptionManager sharedManager];
        _wSocket = [WSocket sharedWSocket];
        _dataArray = [[NSMutableArray alloc]init];
        _fromprice = 0;
        _endprice = 0;
        NSLog(@"_dataArray =%@",_dataArray);
        
        [self initializePopAnimation];
        
        
        [[NSNotificationCenter defaultCenter]addObserver:self
                                                selector:@selector(refreshHeaderLabel)
                                                    name:kFilterDataChange
                                                  object:nil];
        
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    NAVBAR(@"朋友筛选");
    
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, kDeviceWidth, kDeviceHeight-64) style:UITableViewStylePlain];
    _tableView.backgroundColor = [UIColor whiteColor];
    _tableView.estimatedRowHeight = kCellHeight;
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.tableHeaderView = [[UIView alloc]init];
    _tableView.tableFooterView = [[UIView alloc]init];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.dataSource = self;
    _tableView.delegate = self;
    [self.view addSubview:_tableView];
    
    [self customHeaderView];
    
    [[WSocket sharedWSocket]QueryUsersByLocation:0 :-1 :1 :@"" :@"" :0 :0 DfcQueryUsersByLocationBlock:^(int ret, NSDictionary *rootDict)
    {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if (ret>=0)
            {
                if (_dataArray)
                {
                    [_dataArray removeAllObjects];
                }
                NSLog(@"rootDict = %@",rootDict);
                
                for (NSDictionary *dict in [rootDict objectForKey:@"user_list"])
                {
                    DFCUserInfo *userinfo = [[DFCUserInfo alloc]init];
                    [userinfo setValuesForKeysWithDictionary:dict];
                    userinfo.head_portrait = [rootDict objectForKey:@"head_path"];
                    [_dataArray addObject:userinfo];
                }
                [_tableView reloadData];
            }
        });
    }];
}

#pragma mark - View创建工具

-(void)customHeaderView
{
    _headerView = [[MyFriendsHeaderView alloc]initWithFrame:CGRectMake(0, 0, kDeviceWidth, 35.5)];
    _headerView.delegate = self;
    _tableView.tableHeaderView = _headerView;
    
    _filterView = [[QualifyFilterView alloc]initWithFrame:CGRectMake(0, 35-kDeviceHeight, kDeviceWidth, kDeviceHeight-99.5)];
    _filterView.alpha = 0;
    _filterView.delegate = self;
    [_tableView addSubview:_filterView];
    
   // [self refreshHeaderLabel];
    
}

#pragma mark -pop动画效果
-(void)initializePopAnimation
{
    _downAnimation = [_inspManager creatAnimationWithPropName:kPOPViewFrame FunctionName:kCAMediaTimingFunctionEaseIn FromValue:nil ToValue:[NSValue valueWithCGRect:CGRectMake(0, 35, kDeviceWidth, kDeviceHeight-99.5)] Duration:0.2];
    _fadeInAnimaiton = [_inspManager creatAnimationWithPropName:kPOPViewAlpha FunctionName:kCAMediaTimingFunctionEaseIn FromValue:nil ToValue:@(1) Duration:0.2];
    _upAnimation = [_inspManager creatAnimationWithPropName:kPOPViewFrame FunctionName:kCAMediaTimingFunctionDefault FromValue:nil ToValue:[NSValue valueWithCGRect:CGRectMake(0, 35-kDeviceHeight, kDeviceWidth, kDeviceHeight-99.5)] Duration:0.2];
    _fadeOutAnimation = [_inspManager creatAnimationWithPropName:kPOPViewAlpha FunctionName:kCAMediaTimingFunctionEaseOut FromValue:nil ToValue:@(0) Duration:0.2];
    
    __weak FindFrinedsViewController *weakSelf = self;
    [_downAnimation setCompletionBlock:^(POPAnimation *anim, BOOL finished)
    {
        if (finished ==YES)
        {
            [weakSelf.headerView.filterDBtn setEnabled:NO];
        }
    }];
    
    [_upAnimation setCompletionBlock:^(POPAnimation *anim, BOOL finished)
    {
        if (finished ==YES)
        {
            [weakSelf.headerView.filterDBtn setEnabled:YES];
        }
    }];
    
}

#pragma mark - UITabelViewDelegate

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return kCellHeight;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    DFCUserInfo *userinfo = [_dataArray objectAtIndex:indexPath.row];
    NameCardViewController *nameCardVC = [[NameCardViewController alloc]init];
    nameCardVC.userinfo = userinfo;
    [self.navigationController pushViewController:nameCardVC animated:YES];
    
}

#pragma mark - UITableViewDataSource

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"chatlistCell";
    ChatListCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    
    DFCUserInfo *dfcinfo = [_dataArray objectAtIndex:indexPath.row];
    
    if (cell ==nil){
        cell = [[ChatListCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    __weak WSocket *weakSocket = _wSocket;
    [[WSocket sharedWSocket]addDownFileOperationWithFileUrlString:dfcinfo.head_portrait serialId:@"-1" modelType:ModelTypeNormal info:nil downBlock:^(int ret, int isSave, NSData *data, NSString *fileUrl)
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (ret>=0)
            {
                [cell.avatarView setImage:[UIImage imageWithData:data]];
                if (isSave)
                {
                    [data writeToFile:[NSString stringWithFormat:@"%@/%@",kPathAvatar,[weakSocket.lbxManager upper16_MD5:fileUrl]]
                           atomically:YES];
                }
            }
            else
            {
                [cell.avatarView setImage:kDefaultAvatarImage];
            }
        });
        
    }];
    
    cell.nameLabel.text = [NSString stringWithFormat:@"%@",[_inspManager stringFromHexString:dfcinfo.nick_name]];
    cell.lastMSGLabel.text = [NSString stringWithFormat:@"%@",[_inspManager stringFromHexString:dfcinfo.signature]];
    
    NSString *placeStr = [NSString stringWithFormat:@"%@%@%@%@",@"8.0km",dfcinfo.city,dfcinfo.region,dfcinfo.remaining_addr];
    [cell.placeBtn setTitle:placeStr forState:UIControlStateNormal];
    [cell.placeBtn setHidden:NO];
    
    return cell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArray.count;
}

#pragma mark -按钮点击事件
//筛选按钮点击事件
-(void)filterButtonClick:(UIButton *)sender
{
        [_filterView pop_addAnimation:_downAnimation forKey:@"downAnimation"];
        [_filterView pop_addAnimation:_fadeInAnimaiton forKey:@"fadeInAnim"];
    
}

-(void)filterConfrimButtonClick:(UIButton *)sender
{
    if (sender.tag ==0)
    {
        [[WSocket sharedWSocket]QueryUsersByLocation:_place :_sex :_identity :@"" :@"" :_fromprice :_endprice DfcQueryUsersByLocationBlock:^(int ret, NSDictionary *rootDict)
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                
                if (ret>=0) {
                    
                    if (_dataArray)
                    {
                        [_dataArray removeAllObjects];
                    }
                    NSLog(@"backrootdict = %@'",rootDict);
                    
                    for (NSDictionary *dict in [rootDict objectForKey:@"user_list"])
                    {
                        DFCUserInfo *userinfo = [[DFCUserInfo alloc]init];
                        [userinfo setValuesForKeysWithDictionary:dict];
                        userinfo.head_portrait = [rootDict objectForKey:@"head_path"];
                        userinfo.phone_num = [rootDict objectForKey:@"user_id"];
                        userinfo.phone_show_flag = [rootDict objectForKey:@"phone_show_flag"];
                        [_dataArray addObject:userinfo];
                    }
                    NSLog(@"backArray = %@",_dataArray);
                    
                    [_tableView reloadData];
                }
                else
                {
                    [_inspManager showHubAction:ret showView:self.view];
                    //[_inspManager showHudViewLabelText:@"与服务器的连接失效了" detailsLabelText:nil afterDelay:1];
                }
                
            });
        }];
    
    }else if (sender.tag ==1)
    {
        
    }
    
    [_filterView pop_addAnimation:_upAnimation forKey:@"upAnimation"];
    [_filterView pop_addAnimation:_fadeOutAnimation forKey:@"fadeOutAnim"];
}

-(void)refreshHeaderLabel
{
    NSUserDefaults *defaluts = [NSUserDefaults standardUserDefaults];
    NSMutableArray *propArray = [NSMutableArray arrayWithArray:[defaluts objectForKey:kFilterData]];
    NSString *str0 = [NSString stringWithFormat:@"%@,%@",[propArray objectAtIndex:0],[propArray objectAtIndex:1]];
    NSMutableAttributedString *strLabel = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"最近在线(%@)",str0]];
    [strLabel addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:15] range:NSMakeRange(0, 4)];
    
    _headerView.fileterLabel.attributedText =strLabel;
    
    _sex = 0;
    if (![[propArray objectAtIndex:0]isEqualToString:@"全部"])
    {
        _sex = [[propArray objectAtIndex:0]isEqualToString:@"女"] ? 2 : 1;
    }
    _place = [[propArray objectAtIndex:1]isEqualToString:@"全部"] ? 0 :1;
    
    _fromprice = 0;
    _endprice = 0;
    _identity = [[propArray objectAtIndex:2]isEqualToString:@"农民"] ? 1 :2;
    if (_identity ==2)
    {
        NSString *pricestr = [NSString stringWithFormat:@"%@",[propArray objectAtIndex:3]];
        NSLog(@"pricestr = %@",pricestr);
        
        if ([pricestr isEqualToString:@"全部"])
        {
            _fromprice =_endprice = 0;
        }else if ([pricestr isEqualToString:@"0-50"])
        {
            _fromprice = 0;
            _endprice = 50;
        }else if ([pricestr isEqualToString:@"50-100"])
        {
            _fromprice =50;
            _endprice = 100;
        }else if ([pricestr isEqualToString:@"100-150"])
        {
            _fromprice = 100;
            _endprice = 150;
        }else if ([pricestr isEqualToString:@"150-200"])
        {
            _fromprice = 150;
            _endprice =200;
        }
    }
    
    NSLog(@"sex = %d,place = %d,_identity =%d,fromprice = %d,endprice = %d",_sex,_place,_identity,_fromprice,_endprice);
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
